package cn.wang.open.sso.shiro;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

//import cn.wang.open.sso.shiro.filter.AjaxPermissionsAuthorizationFilter;
import cn.wang.open.sso.shiro.filter.ForceLogoutFilter;
import cn.wang.open.sso.shiro.filter.SsoAuthenticationFilter;
import cn.wang.open.sso.shiro.listener.SsoSessionListener;
import cn.wang.open.sso.shiro.realm.UserRealm;
import cn.wang.open.sso.shiro.session.RedisCachingSessionDAO;
import cn.wang.open.sso.shiro.session.SsoSessionFactory;

/**
 * shiro配置类
 */
@Configuration
public class ShiroConfiguration {
	
    private static final Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class);

	@Bean // realm实现，继承自AuthorizingRealm
    public UserRealm userRealm() {
        return new UserRealm();
    }
	
	@Bean // session工厂
    public SessionFactory ssoSessionFactory() {
		return new SsoSessionFactory();
	}

	@Bean // 会话监听器
    public SessionListener ssoSessionListener() {
		return new SsoSessionListener();
	}
	
	@Bean // 会话Cookie模板
    public Cookie sessionIdCookie() {
    	SimpleCookie cookie = new SimpleCookie();
    	 //不会暴露给客户端 
    	cookie.setHttpOnly(true);
    	//设置Cookie的过期时间，秒为单位，默认-1表示关闭浏览器时过期Cookie
    	cookie.setMaxAge(-1);
    	//Cookie名称
    	cookie.setName("sso-server-session-id");
		return cookie;
	}

	@Bean //会话DAO，可重写，持久化session
    public RedisCachingSessionDAO redisCachingSessionDAO() {
        return new RedisCachingSessionDAO();
    }
	
	@Bean // 会话管理器
    public SessionManager sessionManager() {
		DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
		// 全局session超时时间 
		sessionManager.setGlobalSessionTimeout(1800000);
		// sessionDAO
		sessionManager.setSessionDAO(redisCachingSessionDAO());
		sessionManager.setSessionIdCookieEnabled(true);
		sessionManager.setSessionIdCookie(sessionIdCookie());
		sessionManager.setSessionValidationSchedulerEnabled(false);
		List<SessionListener> listeners = new ArrayList<>();
		listeners.add(ssoSessionListener());
		sessionManager.setSessionListeners(listeners);
		sessionManager.setSessionFactory(ssoSessionFactory());
		return sessionManager;
	}
	
    @Bean
    public RememberMeManager rememberMeManager() {
    	CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
    	//TODO rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度（128 256 512 位）
    	rememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
    	SimpleCookie cookie = new SimpleCookie("rememberMe");
    	// 不会暴露给客户端
    	cookie.setHttpOnly(true);
    	// 记住我cookie生效时间
    	cookie.setMaxAge(2592000);
    	rememberMeManager.setCookie(cookie);
    	
    	return rememberMeManager;
    }
    
    @Bean(name = "shiroFilter") // Shiro的Web过滤器
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //Shiro的核心安全接口,这个属性是必须的
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //SecurityUtils.setSecurityManager(securityManager);
        
        shiroFilterFactoryBean.setLoginUrl("http://127.0.0.1:1111");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        //TODO filterMap.put("authc", new AjaxPermissionsAuthorizationFilter());
        // 重写authc过滤器
        filterMap.put("authc", new SsoAuthenticationFilter());
        // 强制退出会话过滤器
        filterMap.put("forceLogoutFilter", new ForceLogoutFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        
        /*定义shiro过滤链  Map结构
         * Map中key(xml中是指value值)的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的
         * anon：它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种
         * authc：该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter
         */
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
         /* 过滤链定义，从上向下顺序执行，一般将 / ** 放在最为下边:这是一个坑呢，一不小心代码就不好使了;
          authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问 */
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/sso/**", "anon");
        filterChainDefinitionMap.put("/error", "anon");
        filterChainDefinitionMap.put("/**", "forceLogoutFilter, authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        
        return shiroFilterFactoryBean;
    }
    
    @Bean  // 安全管理器
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm());
        securityManager.setSessionManager(sessionManager());
        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     * 所以我们需要修改下doGetAuthenticationInfo中的代码;
     * ）
     * 可以扩展凭证匹配器，实现 输入密码错误次数后锁定等功能，下一次
     
    @Bean(name = "credentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //散列的次数，比如散列两次，相当于 md5(md5(""));
        hashedCredentialsMatcher.setHashIterations(2);
        //storedCredentialsHexEncoded默认是true，此时用的是密码加密用的是Hex编码；false时用Base64编码
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }*/

    /**
     * Shiro生命周期处理器
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
     */
    @Bean
    @DependsOn({"lifecycleBeanPostProcessor"})
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }
}
